package com.springboot.last_experiment.securityutil;

/**
 * @author Chb
 * date 2020-06-26
 */

import com.springboot.last_experiment.dao.AdminDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {


  @Autowired
  AdminDao adminDao;

  @Override
  public Authentication authenticate(Authentication authentication)
      throws AuthenticationException {
    System.out.println("now start custom authenticate process!");
    MyWebAuthenticationDetails details = (MyWebAuthenticationDetails) authentication.getDetails();


    //验密
    String inpass="";
    try {
      inpass = adminDao.getByName(details.getUsername()).getAdminPass();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if(!inpass.equals(details.getPassword())) {
      System.out.println("password error");
      throw new BadCredentialsException("authenticate fail！");
    }


    Collection<GrantedAuthority> auths=new ArrayList<GrantedAuthority>();
    auths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    return new UsernamePasswordAuthenticationToken(adminDao.getByName(details.getUsername()), details.getPassword(),auths);

  }

  @Override
  public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
  }

}
